package com.tbynet.jwp.service.impl;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core.JwpService;
import com.tbynet.jwp.service.spi.CommentManager;
import com.tbynet.jwp.repository.spi.CommentService;
import com.tbynet.jwp.repository.spi.PostService;

import java.sql.SQLException;
import java.util.List;

/**
 * 评论服务编排管理类
 * @ClassName: CommentManager
 * @Description: 负责评论相关业务的编排和事务管理，协调多个Service完成复杂业务操作
 * @Author: 佰亿互联
 * @Date: 2025年11月4日
 *
 * @Copyright: 2025 www.tbynet.com Inc. All rights reserved.
 * 注意: 本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */
@Aop(CommentManager.class)
public class CommentServiceImpl extends JwpService implements CommentManager {

    @Inject
    private CommentService commentService;

    @Inject
    private PostService postService;

    /**
     * 批量审核评论
     * @param commentIds 评论ID数组
     * @param status 目标状态
     * @return 操作结果
     */
    public Ret batchApproveComments(String[] commentIds, String status) {
        log.info("开始批量审核评论，评论数量：{}，目标状态：{}", commentIds.length, status);

        if (commentIds == null || commentIds.length == 0) {
            return Ret.fail("msg", "请选择要操作的评论");
        }

        boolean success = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                try {
                    for (String commentId : commentIds) {
                        if (!commentService.updateCommentStatus(commentId, status)) {
                            log.error("更新评论状态失败，评论ID：{}", commentId);
                            return false;
                        }
                    }
                    return true;
                } catch (Exception e) {
                    log.error("批量审核评论事务执行失败", e);
                    throw new SQLException("批量审核评论事务失败", e);
                }
            }
        });

        if (success) {
            log.info("批量审核评论成功，评论数量：{}，目标状态：{}", commentIds.length, status);
            return Ret.ok("msg", getBatchOperationMessage(status));
        } else {
            log.error("批量审核评论失败，评论数量：{}，目标状态：{}", commentIds.length, status);
            return Ret.fail("msg", "操作失败");
        }
    }

    /**
     * 批量删除评论
     * @param commentIds 评论ID数组
     * @return 删除结果
     */
    public Ret batchDeleteComments(String[] commentIds) {
        log.info("开始批量删除评论，评论数量：{}", commentIds.length);

        if (commentIds == null || commentIds.length == 0) {
            return Ret.fail("msg", "请选择要删除的评论");
        }

        boolean success = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                try {
                    for (String commentId : commentIds) {
                        if (!deleteSingleComment(commentId)) {
                            log.error("删除评论失败，评论ID：{}", commentId);
                            return false;
                        }
                    }
                    return true;
                } catch (Exception e) {
                    log.error("批量删除评论事务执行失败", e);
                    throw new SQLException("批量删除评论事务失败", e);
                }
            }
        });

        if (success) {
            log.info("批量删除评论成功，评论数量：{}", commentIds.length);
            return Ret.ok("msg", "批量删除评论成功");
        } else {
            log.error("批量删除评论失败，评论数量：{}", commentIds.length);
            return Ret.fail("msg", "批量删除评论失败");
        }
    }

    /**
     * 获取评论分页列表（带文章信息）
     * @param status 评论状态
     * @param pageNumber 页码
     * @param pageSize 每页大小
     * @return 评论分页数据
     */
    public Page<Record> getCommentListWithPostInfo(String status, int pageNumber, int pageSize) {
        Page<Record> commentPage = commentService.getCommentPageByStatus(status, pageNumber, pageSize);

        // 丰富评论信息，添加文章标题等
        for (Record comment : commentPage.getList()) {
            enrichCommentInfo(comment);
        }

        return commentPage;
    }

    /**
     * 获取文章评论统计
     * @param postId 文章ID
     * @return 评论统计信息
     */
    public Record getPostCommentStats(Object postId) {
        Record stats = new Record();

        // 总评论数
        int totalComments = commentService.countByPostId(postId);
        stats.set("total_comments", totalComments);

        // 待审核评论数
        String[] postIds = {postId.toString()};
        List<Record> pendingStats = commentService.getPendingCommentsCount(postIds);
        int pendingCount = getPendingCountFromStats(pendingStats, postId);
        stats.set("pending_comments", pendingCount);

        return stats;
    }

    /**
     * 获取评论详情
     * @param commentId 评论ID
     * @return 评论详情
     */
    public Record getCommentDetail(String commentId) {
        return commentService.getCommentDetail(commentId);
    }

    // ============ 私有方法 ============

    /**
     * 删除单条评论（包含元数据）
     * @param commentId 评论ID
     * @return 删除结果
     */
    private boolean deleteSingleComment(String commentId) {
        // 1. 删除评论元数据
        if (!commentService.deleteCommentMeta(commentId)) {
            log.warn("删除评论元数据失败，评论ID：{}", commentId);
            // 继续执行，不中断
        }

        // 2. 删除评论本身
        return commentService.deleteById(commentId);
    }

    /**
     * 从统计结果中获取待审核评论数量
     * @param pendingStats 待审核统计列表
     * @param postId 文章ID
     * @return 待审核评论数量
     */
    private int getPendingCountFromStats(List<Record> pendingStats, Object postId) {
        if (pendingStats == null || pendingStats.isEmpty()) {
            return 0;
        }

        String postIdStr = postId.toString();
        for (Record record : pendingStats) {
            Object recordPostId = record.get("comment_post_ID");
            if (recordPostId != null && postIdStr.equals(recordPostId.toString())) {
                Integer count = record.getInt("num_comments");
                return count != null ? count : 0;
            }
        }

        return 0;
    }

    /**
     * 丰富评论信息
     */
    private void enrichCommentInfo(Record comment) {
        try {
            // 如果评论详情中已经包含文章标题，则不需要再次查询
            if (comment.get("post_title") == null) {
                Object commentId = comment.get("comment_ID");
                if (commentId != null) {
                    Record commentDetail = commentService.getCommentDetail(commentId.toString());
                    if (commentDetail != null && commentDetail.get("post_title") != null) {
                        comment.set("post_title", commentDetail.get("post_title"));
                    }
                }
            }
        } catch (Exception e) {
            log.error("丰富评论信息异常，评论ID：{}", comment.get("comment_ID"), e);
        }
    }

    /**
     * 获取批量操作消息
     */
    private String getBatchOperationMessage(String status) {
        switch (status) {
            case "1":
                return "批量审核通过成功";
            case "0":
                return "批量待审核设置成功";
            case "spam":
                return "批量标记为垃圾评论成功";
            case "trash":
                return "批量移至回收站成功";
            default:
                return "操作成功";
        }
    }
}